package gpr.view;

import gpr.view.R.id;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;


public class GPRViewActivity extends Activity
{
	private static final String LOG_TAG = "GPRViewActivity";
	
	private String		nomeMappaCorrente;
	private double[][] 	mat;
	private double 		min;
	private double	 	max;
	private int 		rows;
	private int 		cols;
	private double 		radar_freq;
	private double 		rx_freq;
	private double 		rx_x0;
	private double 		rx_y0;
	private double 		rx_alpha;
	private double 		tx_alpha;
	private double 		tx_freq;
		
	private Handler 	handler = new Handler();
	
	
	private void loadMat(String nomeMappa)
	{
		if (nomeMappa.equals(this.nomeMappaCorrente))
			return;
		
		this.nomeMappaCorrente = nomeMappa;

		if (nomeMappa.startsWith("http://"))
			loadMatFromUrl(nomeMappa);
		else
			loadMatFromAssets(nomeMappa);
	}
	
	private void loadMatFromAssets(String nomeMappa)
	{	
		InputStream is = null;
		BufferedReader in = null;
		
		try 
		{
			AssetManager am = this.getAssets();
			is = am.open(nomeMappa);
			Log.d(LOG_TAG, "file aperto con successo");

			in = new BufferedReader(new InputStreamReader(is));
			loadMatFromReader(in);

		} catch (IOException e) {
			Log.e(LOG_TAG, e.getMessage());
			
			handler.post(new Runnable()
			{
				public void run()
				{
					AlertDialog alertDialog = new AlertDialog.Builder(GPRViewActivity.this).create();
					alertDialog.setTitle("Errore");
					alertDialog.setMessage("File non trovato");
					alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
					   public void onClick(DialogInterface dialog, int which) {
					   }
					});
					alertDialog.show();
				}
			});
		}
		finally
		{
			try {
				is.close();
				in.close();
			} catch (Exception e) {
			}
		}
	}

	private void loadMatFromUrl(String nomeMappa)
	{
		InputStream is = null;
		BufferedReader in = null;

		is = Http.getHttpInputStream(nomeMappa);
		if (is != null)
		{
			Log.d(LOG_TAG, "url aperta con successo");

			in = new BufferedReader(new InputStreamReader(is));
			loadMatFromReader(in);

			try {
				is.close();
				in.close();
			} catch (Exception e) {
			}
		}
		else
		{
			Log.e(LOG_TAG, "url non trovata");
			
			handler.post(new Runnable()
			{
				public void run()
				{
					AlertDialog alertDialog = new AlertDialog.Builder(GPRViewActivity.this).create();
					alertDialog.setTitle("Errore");
					alertDialog.setMessage("File non trovato");
					alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
					   public void onClick(DialogInterface dialog, int which) {
					   }
					});
					alertDialog.show();
				}
			});
		}
			
	}

	private void loadMatFromReader(BufferedReader in)
	{
		try
		{	
			rows = Integer.parseInt(in.readLine());
			cols = Integer.parseInt(in.readLine());
			radar_freq = Double.parseDouble(in.readLine());
			rx_freq = Double.parseDouble(in.readLine());
			rx_x0 = Double.parseDouble(in.readLine());
			rx_y0 = Double.parseDouble(in.readLine());
			rx_alpha = Double.parseDouble(in.readLine());
			tx_alpha = Double.parseDouble(in.readLine());
			tx_freq = Double.parseDouble(in.readLine());
			
			mat = new double[rows][cols];
			
			String line;

			/*
			 * Leggi per colonne
			 */
			
			line = in.readLine();
			StringTokenizer st = new StringTokenizer(line, " ");
			
			for(int j=0; j<cols; j++)
			{
				for(int i=0; i<rows; i++)
				{
					if (!st.hasMoreTokens())
						break;
					
					String token = st.nextToken();
					Double value = Double.parseDouble(token);
					mat[i][j] = value;
					
				}
			}
			
			/*
			 * Leggi per righe
			 * 
			//int i=0;
			//while ( (line = in.readLine()) != null )
			for(int i=0; i<rows; i++)
			{
				line = in.readLine();
				
				if (line == null)
					break;
				
				StringTokenizer st = new StringTokenizer(line, ",");
				//int j=0;
				//while(  st.hasMoreTokens())
				for(int j=0; j<cols; j++)
				{
					if (!st.hasMoreTokens())
						break;
					
					String token = st.nextToken();
					Double value = Double.parseDouble(token);
					mat[i][j] = value;
					
					//j++;
				}
				
				//i++;
			}
			*/
			
			min = mat[0][0];
			max = mat[0][0];
			for(int i=0; i<mat.length; i++)
				for(int j=0; j<mat[0].length; j++)
				{
					if (mat[i][j] < min)
						min = mat[i][j];
					if (mat[i][j] > max)
						max = mat[i][j];
				}			
		}
		catch(Exception e)
		{
			Log.e(LOG_TAG, e.getClass().getName() + ": " + e.getMessage());
		}

	}

	private Bitmap createBitmapFromMat(boolean bianconero)
	{
		if (mat == null)
			return null;
		
		Bitmap bitmap = Bitmap.createBitmap(mat[0].length, mat.length, Bitmap.Config.ARGB_8888);

		for(int i=0; i<mat.length; i++)
			for(int j=0; j<mat[0].length; j++)
			{
				double value = mat[i][j];			
				int r,g,b;

				if (bianconero)
				{
					//Bianco/Nero: nero=min, bianco=max
					/*
					double range = max - min;				
					int color = 255 - (int) (((value-min) / range) * 255);
					
					r = color;
					g = color;
					b = color;
					*/
					
					//Bianco/Nero: bianco=min, nero=0, bianco=max
					int color;
					
					if (value >= 0)
					{
						color = (int)((value / max) * 255);
						r = color;
						g = color;
						b = color;
					}
					else
					{
						color = (int) ((value / min) * 255);

						r = color/4;
						g = color/4;
						b = color/4;
					}
				}
				else
				{
					int color;					
					
					if (value >= 0)
					{
						color = (int)((value / max) * 255);
						r = color;
						g = (255-color)/2;
						b = 0;
					}
					else
					{
						color = (int) ((value / min) * 255);

						r = 0;
						g = (255-color)/2;
						b = color;
					}
				}
				
				bitmap.setPixel(j, i, Color.argb(255, r, g, b));
			}
		
		return bitmap;
	}
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        

        
        
        final Button btnBianconero = (Button) findViewById(id.btnBianconero);
        final Button btnColori = (Button) findViewById(id.btnColori);
        final Button btnInfo = (Button) findViewById(id.btnInfo);
        final TouchImageView imageView = (TouchImageView) findViewById(R.id.imageView);
        final EditText editText = (EditText) findViewById(R.id.editText);
        final TextView pleaseWait = (TextView) findViewById(R.id.pleaseWait);
        final LinearLayout legendLayout = (LinearLayout) findViewById(R.id.legendLayout);
        
       
        btnBianconero.setOnClickListener(new View.OnClickListener()
        {	
			
			public void onClick(View v)
			{				
				pleaseWait.setVisibility(View.VISIBLE);
				imageView.setVisibility(View.GONE);
				
				Timer timer = new Timer();
				TimerTask timerTask = new TimerTask()
				{
					@Override
					public void run()
					{
				        loadMat(editText.getText().toString());
				        final Bitmap bitmap = createBitmapFromMat(true);        

				        handler.post(new Runnable()
				        {
				        	
				        	public void run()
				        	{
						        imageView.setImageBitmap(bitmap);
						        pleaseWait.setVisibility(View.GONE);
						        imageView.setVisibility(View.VISIBLE);				        		
				        	}				    
				        });
					}
					
				};

				timer.schedule(timerTask, 1500);
			}
		});   

        btnColori.setOnClickListener(new View.OnClickListener()
        {	
			
			public void onClick(View v)
			{				
				pleaseWait.setVisibility(View.VISIBLE);
				imageView.setVisibility(View.GONE);
				
				Timer timer = new Timer();
				TimerTask timerTask = new TimerTask()
				{
					@Override
					public void run()
					{
				        loadMat(editText.getText().toString());
				        final Bitmap bitmap = createBitmapFromMat(false);        

				        handler.post(new Runnable()
				        {
				        	
				        	public void run()
				        	{
						        imageView.setImageBitmap(bitmap);
						        pleaseWait.setVisibility(View.GONE);
						        imageView.setVisibility(View.VISIBLE);				        		
				        	}				    
				        });
					}
					
				};

				timer.schedule(timerTask, 1500);
			}
		});   

        btnInfo.setOnClickListener(new View.OnClickListener()
        {	
			
			public void onClick(View v)
			{	
				final String info = 
					"rows = " + rows + "\n" +
					"cols = " + cols + "\n" +
					"radar_freq = " + radar_freq + "\n" +
					"rx_freq = " + rx_freq + "\n" +
					"rx_x0 = " + rx_x0 + "\n" +
					"rx_y0 = " + rx_y0 + "\n" +
					"rx_alpha = " + rx_alpha + "\n" +
					"tx_alpha = " + tx_alpha + "\n" +
					"tx_freq = " + tx_freq + "\n";
						
				handler.post(new Runnable()
				{
					public void run()
					{
						AlertDialog alertDialog = new AlertDialog.Builder(GPRViewActivity.this).create();
						alertDialog.setTitle("Info");
						alertDialog.setMessage(info);
						alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
						   public void onClick(DialogInterface dialog, int which) {
						   }
						});
						alertDialog.show();
					}
				});
			}
		});   
    }
}